<template>
	<el-card class="layout-query">
		<el-form ref="queryFormRef" :inline="true">
			<el-form-item label="咨询时间">
				<el-date-picker v-model="state.queryParams.consultDate" type="date" value-format="YYYY-MM-DD HH:mm:ss" />
			</el-form-item>
			<el-form-item label="是否公开">
				<el-select v-model="state.queryParams.hasPublic">
					<el-option v-for="item in gklist" :key="item.value" :label="item.name" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="标准名称">
				<el-input v-model="state.queryParams.standardName" placeholder="标准名称"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card>
		<el-space alignment="end" size="10" wrap style="width: 100%; justify-content: flex-end">
			<el-button v-auth="'M004_CancelPublish'" type="primary" @click="handleCancel">取消发布</el-button>
			<el-button v-auth="'M004_SendMessage'" type="primary" @click="handleRemind">发送提醒</el-button>
			<!-- <el-space>
				<el-button type="primary" @click="handleSend">发布/取消发布</el-button>
			</el-space> -->
		</el-space>
		<el-table
			ref="tableRef"
			v-loading="state.dataListLoading"
			:data="state.dataList"
			class="mt15"
			stripe
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" />
			<el-table-column type="index" label="序号" align="center" />
			<el-table-column label="标准名称" align="center" prop="standardName" />
			<el-table-column key="" label="咨询人" align="center" prop="consultant"> </el-table-column>
			<el-table-column label="咨询日期" align="center" prop="consultDate"> </el-table-column>
			<el-table-column label="联系地址" align="center" prop="contactAddress"> </el-table-column>
			<el-table-column label="联系电话" align="center" prop="contactTel"> </el-table-column>
			<el-table-column label="电子邮件" align="center" prop="contactEmail"> </el-table-column>
			<el-table-column label="咨询内容" align="center" prop="consultContent"> </el-table-column>
			<el-table-column label="是否公开" align="center" prop="hasPublic"> </el-table-column>
			<el-table-column label="回复内容" align="center" prop="replyContent">
				<template #default="{ row }">
					<el-tooltip effect="dark" :content="row.replyContent" placement="top" popper-class="custom-tooltip">
						<div class="truncate-text">{{ formatContent(row.replyContent) }}</div>
					</el-tooltip>
				</template>
			</el-table-column>
			<el-table-column label="回复人" align="center" prop="replyPerson"> </el-table-column>
			<el-table-column label="回复日期" align="center" prop="replyDate"> </el-table-column>
			<el-table-column label="状态" align="center" prop="publishStatus"> </el-table-column>

			<el-table-column label="操作" width="90" fixed="right" header-align="center" align="center">
				<template #default="scope">
					<el-icon
						v-auth="'M004_Reply'"
						:size="16"
						color="#1491FF"
						title="回复"
						style="cursor: pointer; margin: 0 6px"
						@click="replyHandle(scope.row.id)"
					>
						<ChatLineRound />
					</el-icon>

					<el-icon
						v-if="scope.row.publishStatus == '未发布'"
						v-auth="'M004_Publish'"
						:size="16"
						color="#1491FF"
						title="发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleSend(scope.row.id, 1)"
					>
						<CircleCheck />
					</el-icon>

					<el-icon
						v-if="scope.row.publishStatus == '已发布'"
						v-auth="'M004_CancelPublish'"
						:size="16"
						color="#1491FF"
						title="取消发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleSend(scope.row.id, 0)"
					>
						<CircleClose />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.queryParams.pageNum"
			:page-size="state.queryParams.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>
	</el-card>

	<feedbackadd ref="feedbackaddRef" v-model:visible="fvisible" @refresh-data-list="getDataList"></feedbackadd>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import feedbackadd from './components/feedbackadd.vue'

import { consultNoticeApi, consultReplyListApi, consultReplyOrNoApi } from '@/api/standardapplication/index'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { t } from 'vxe-table'

const state = reactive({
	queryParams: {
		consultDate: '',
		hasPublic: '',
		standardName: '',
		pageNum: 1,
		pageSize: 10
	},
	total: 1,
	dataListLoading: false,
	dataList: [],
	ids: []
})
// 是否公开 0：公开  1：未公开
const gklist = [
	{ name: '全部', value: ' ' },
	{ name: '公开', value: 0 },
	{ name: '不公开', value: 1 }
]
const fvisible = ref(false)
const queryFormRef = ref()
const tableRef = ref<InstanceType<typeof ElTable>>()
const feedbackaddRef = ref()

// 列表数据获取
const reset = () => {
	state.queryParams.consultDate = ''
	state.queryParams.hasPublic = ''
	state.queryParams.standardName = ''
	state.queryParams.pageNum = 1
	state.queryParams.pageSize = 10
	getDataList()
}

const isContentOverflow = (content: String) => {
	console.log(content, 'sgsgsgsgsg')
	// 处理空值
	if (!content) return false;
	return content.split('\n').length > 3
	// return true;
}
const formatContent = (content: String) => {
	// 处理空值
	if (!content) return '';
	return content.split('\n').slice(0, 4).join('\n')
	// return content;
}
const handleSearch = () => {
	state.queryParams.pageNum = 1
	getDataList()
}

const getDataList = async () => {
	state.dataListLoading = true
	await consultReplyListApi(state.queryParams).then(res => {
		// console.log(res.data.list)
		state.dataListLoading = false
		state.dataList = res.data.list
		state.total = res.data.total || 0
	})
}

const handleCurrentChange = (val: number) => {
	state.queryParams.pageNum = val
	getDataList()
}
const handleSizeChange = (val: number) => {
	state.queryParams.pageSize = val
	getDataList()
}

const replyHandle = (val: number) => {
	feedbackaddRef.value.init(true, val)
	fvisible.value = true
}
// 选择数据
interface dataObj {
	id: string | Number
	standardName: string
	projectInfoId: string
	consultant: string
	contactAddress: string
	contactTel: string
	contactEmail: string
	consultContent: string
	consultDate: string
	hasPublic: string
	hasNoticed: string
	replyContent: string
	replyDate: string
	replyPerson: string
	consultStatus: string
	publishStatus: string
}
const multipleSelection = ref<dataObj[]>([])
const handleSelectionChange = (val: dataObj[]) => {
	multipleSelection.value = val
	state.ids = multipleSelection.value.map(item => item.id)
}

const handleSend = async (id: Number | String, type: Number) => {
	// if(state.ids.length <= 0) {
	// 	ElMessage({
	// 		type: 'warning',
	// 		message: '请选择发布数据',
	// 	})
	// 	return
	// }
	let params = {
		ids: [id]
	}

	if (type == 1) {
		ElMessageBox.confirm('是否确认发布?', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				consultReplyOrNoApi(params, type).then(res => {
					// console.log('发布:', res.data)
					if (res['success']) {
						ElMessage({
							type: 'success',
							message: '操作成功'
						})
						// multipleSelection.value = []
						// tableRef.value!.clearSelection()
						getDataList()
					}
				})
			})
			.catch(() => {})
	} else {
		ElMessageBox.confirm('是否取消发布?', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				consultReplyOrNoApi(params, type).then(res => {
					// console.log('发布:', res.data)
					if (res['success']) {
						ElMessage({
							type: 'success',
							message: '操作成功'
						})
						// multipleSelection.value = []
						// tableRef.value!.clearSelection()
						getDataList()
					}
				})
			})
			.catch(() => {})
	}
}

const handleCancel = () => {
	if (state.ids.length <= 0) {
		ElMessage({
			type: 'warning',
			message: '请选择取消发布的数据'
		})
		return
	}
	const allPermissionValid = multipleSelection.value.every(row => row.publishStatus == '已发布')
	if (!allPermissionValid) {
		ElMessage({
			type: 'warning',
			message: '请选择已发布的数据'
		})
		return
	}
	let params = {
		ids: state.ids
	}
	ElMessageBox.confirm('是否取消发布?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			consultReplyOrNoApi(params, 0).then(res => {
				ElMessage({
					type: 'success',
					message: '操作成功'
				})
				getDataList()
			})
		})
		.catch(() => {})

	console.log(params)
}

// 发送提醒
const handleRemind = async () => {

	if (state.ids.length <= 0) {
		ElMessage({
			type: 'warning',
			message: '请选择发送提醒的数据'
		})
		return
	}
	let params = {
		ids: state.ids
	}
	
	let allContactTels = multipleSelection.value.map(item => item.contactTel);

	// 新的模拟发送短信的前端代码 2025.10.13
	ElMessageBox.confirm('是否发送短信提醒?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			ElMessage({
				type: 'success',
				message: `操作成功，已向用户【${allContactTels.join(', ')}】发送短信`
			});
		})
		.catch(() => {
			console.log('取消发送短信')
		})

	// 旧的真实发送短信的前端代码 2025.10.13
	// await consultNoticeApi(params).then(res => {
	// 	// console.log('发布:', res.data)
	// 	if (res['success']) {
	// 		ElMessage({
	// 			type: 'success',
	// 			message: '操作成功'
	// 		})
	// 		multipleSelection.value = []
	// 		tableRef.value!.clearSelection()
	// 		getDataList()
	// 	}
	// })
}

onMounted(() => {
	getDataList()
})
</script>

<style lang="scss" scoped>
.truncate-text {
	display: -webkit-box;
	-webkit-line-clamp: 4;
	-webkit-box-orient: vertical;
	overflow: hidden;
	line-height: 1.5;
}
</style>
<style>
.custom-tooltip {
	max-width: 400px;
	/* 限制最大宽度 */
	word-wrap: break-word;
	/* 允许长单词或URL换行 */
}
</style>
